//
// Created by jaesonzhang on 2024/3/19.
//

#ifndef CPPSQLITE_SQLITEMANAGER_H
#define CPPSQLITE_SQLITEMANAGER_H


#include <string>
#include <sqlite3.h>
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <functional>
#include <future>

class SQLiteManager {
public:
    SQLiteManager(const std::string &db_path);

    ~SQLiteManager();

    // 异步执行SQL查询
    std::future<void> executeAsync(const std::string &sql);

    std::future<sqlite3_stmt *> prepareAsync(const std::string &sql);

private:
    sqlite3 *db_ = nullptr;
    std::thread db_thread_;
    std::queue<std::packaged_task<void()>> tasks_;
    std::mutex task_mutex_;
    std::condition_variable task_cv_;
    bool stop_thread_;

    // 将任务添加到队列中
    template<typename T>
    void enqueueTask(T &&task);

    // 数据库线程的主循环
    void processTasks();
};


#endif //CPPSQLITE_SQLITEMANAGER_H
